package com.zcy;

import com.espertech.esper.common.client.EventBean;
import com.espertech.esper.runtime.client.EPEventService;
import com.zcy.event.MyEvent;
import com.zcy.util.EsperBuilder;
import com.zcy.util.TimeUtils;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.Test;

import java.util.concurrent.TimeUnit;

/**
 * 14.3.7. Time-Length Combination Batch Window (time_length_batch or win:time_length_batch)
 */
@Slf4j
public class TimeLengthBatchWindow extends TimeUtils {

    private static final String _TimeLengthWindow = "@name('time_length_batch_window') select sum(num) from MyEvent#time_length_batch(2 sec, 2)";

    /**
     * 这是TimeBatch与LengthBatch的组合，哪一个先到达触发条件则先执行
     * sum is : 30
     * sum is : null
     * sum is : 30
     * sum is : null
     * sum is : 40
     * sum is : null
     */
    @Test
    public void lengthWindowTest() {
        EsperBuilder esperBuilder = new EsperBuilder(_TimeLengthWindow, new Class[]{MyEvent.class});

        esperBuilder.startCompile();

        EPEventService epEventService = esperBuilder.startDeploy((eventBeans, eventBeans1, epStatement, epRuntime) -> {
            for (int i = 0; i < eventBeans.length; i++) {
                EventBean eventBean = eventBeans[i];
                log.info("sum is : {}", eventBean.get("sum(num)"));
            }
        });

        epEventService.sendEventBean(MyEvent.builder().timestamp(System.currentTimeMillis()).amount("001").name("001-name").num(10).build(), MyEvent.class.getSimpleName());
        sleep(TimeUnit.MILLISECONDS, 1899L);
        epEventService.sendEventBean(MyEvent.builder().timestamp(System.currentTimeMillis()).amount("002").name("002-name").num(20).build(), MyEvent.class.getSimpleName());
        sleep(TimeUnit.MILLISECONDS, 2899L);
        epEventService.sendEventBean(MyEvent.builder().timestamp(System.currentTimeMillis()).amount("003").name("003-name").num(30).build(), MyEvent.class.getSimpleName());
        sleep(TimeUnit.MILLISECONDS, 3899L);
        epEventService.sendEventBean(MyEvent.builder().timestamp(System.currentTimeMillis()).amount("004").name("004-name").num(40).build(), MyEvent.class.getSimpleName());

        sleep(TimeUnit.SECONDS, 40L);
    }

}
